<template>
	<jk-dialog
		v-model="showDialog"
		:title="`${dataId ? '编辑' : '新增'}-生产投料合计`"
		width="600px"
		:show-content-loading="showLoading"
		:confirm-btn-loading="saveBtnLoading"
		append-to-body
		:fullscreen="false"
		:permission-prefix="permissionPrefix"
		@on-cancel="onVisibleChange(false)"
		@on-visible-change="onVisibleChange"
		@on-confirm="onConfirmBtn('save')"
	>
		<el-form
			ref="ruleForm"
			:model="ruleForm"
			:rules="rules"
			label-width="80px"
			:show-message="false"
		>
			<el-row ref="box1">
				<div>
					<div>
						<el-col :span="24">
							<el-form-item
								class="margin-bottom-10"
								label-width="100px"
								label="投料日期"
								prop="belongDate"
							>
								<jk-date-picker
									v-model="ruleForm.belongDate"
									size="medium"
									placeholder="投料时间"
									@change="onDateTimeChange"
								/>
							</el-form-item>
						</el-col>
						<el-col :span="24">
							<el-form-item
								class="margin-bottom-10"
								label-width="100px"
								label="投料班次"
								prop="shiftId"
							>
								<el-select
									v-model="ruleForm.shiftId"
									clearable
									placeholder="报工班次"
									class="width-100-percent"
									@change="onScheduleShiftChange"
								>
									<el-option
										v-for="(item, index) in shiftList"
										:key="item.id"
										:label="item.name"
										:value="item.id"
									></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col
							v-for="(item, index) in ruleForm.empList"
							:key="item.id || index"
							:span="24"
						>
							<div class="flex-start">
								<el-form-item
									class="margin-bottom-10"
									label-width="100px"
									label="投料人"
									:prop="`empList[${index}].id`"
								>
									<el-select
										v-model="ruleForm.empList[index].id"
										placeholder="请选择"
										:disabled="!ruleForm.shiftId"
										class="width-100-percent"
										@change="onStaffListChange(index)"
									>
										<!-- :label="i.empName" -->
										<el-option
											v-for="i in staffList"
											:key="i.empId"
											:label="isEmpDisabled(i.empId, index) ? i.empName + '（已选）' : i.empName"
											:disabled="isEmpDisabled(i.empId, index)"
											:value="i.empId"
										/>
									</el-select>
								</el-form-item>

								<el-form-item
									class="margin-bottom-10"
									label-width="100px"
									label="投料占比"
									:prop="`empList[${index}].feedstockPercentage`"
								>
									<jk-input
										v-model="
											ruleForm.empList[index]
												.feedstockPercentage
										"
									></jk-input>
								</el-form-item>

								<div class="flex-start margin-left-10">
									<el-button
										size="small"
										type="primary"
										icon="el-icon-circle-plus"
										circle
										@click="onAddFeedstock"
									></el-button>
									<el-button
										size="small"
										:disabled="index === 0"
										type="danger"
										icon="el-icon-remove"
										circle
										@click="onDelFeedstock(index)"
									></el-button>
								</div>
							</div>
						</el-col>
						<el-col :span="24">
							<el-form-item
								class="margin-bottom-10"
								label-width="100px"
								label="清花线"
								prop="productionLineId"
							>
								<jk-select
									v-model="ruleForm.productionLineId"
									size="medium"
									class="width-100-percent"
									:option-list="productionLineList"
									value-key-name="id"
									label-key-name="name"
									placeholder="产线"
									@change="onPrdLineChange"
								></jk-select>
							</el-form-item>
						</el-col>
						<el-col :span="24">
							<el-form-item
								class="margin-bottom-10"
								label-width="100px"
								label="品种"
							>
								<span class="read-only-2">{{
									ruleForm.productName
								}}</span>
							</el-form-item>
						</el-col>
						<el-col :span="24">
							<el-form-item
								class="margin-bottom-10"
								label-width="100px"
								label="批号"
							>
								<span class="read-only-2">{{
									ruleForm.batchCode
								}}</span>
							</el-form-item>
						</el-col>
						<el-col :span="24">
							<el-form-item
								class="margin-bottom-10"
								label-width="100px"
								label="仓数"
								prop="warehouseNumber"
							>
								<jk-input
									v-model="ruleForm.warehouseNumber"
									@change="onWarehouseChange"
								></jk-input>
							</el-form-item>
						</el-col>
						<el-col :span="24">
							<el-form-item
								class="margin-bottom-10"
								label-width="100px"
								label="总重(吨)"
							>
								<jk-input
									v-model="ruleForm.allQty"
									disabled
								></jk-input>
							</el-form-item>
						</el-col>
						<el-col :span="24">
							<el-form-item
								class="margin-bottom-10"
								label-width="100px"
								label="每仓重量(吨)"
							>
								<div style="display: flex; align-items: center">
									<jk-input
										v-model="weightCode"
										disabled
									></jk-input>
									<el-popover
										v-model="visible"
										placement="bottom"
										width="200"
									>
										<div
											style="
                                                display: flex;
                                                text-align: right;
                                                margin: 0;
                                            "
										>
											<jk-input
												v-model="weight"
												size="mini"
											></jk-input>
											<el-button
												type="primary"
												size="mini"
												@click="onWeight"
											>确定</el-button>
										</div>
										<el-button
											slot="reference"
										>修改</el-button>
									</el-popover>
								</div>
							</el-form-item>
						</el-col>
					</div>
				</div>
			</el-row>
		</el-form>
	</jk-dialog>
</template>

<script>
    import calHeight from '/src/mixins/cal-dialog-height';
    import { formatDate, formatTime, tipsBar } from '../../../../utils/jk/jk-tool';
    import { workforcemanagementScheduleList } from '../../../../api/schedule/scheduling';
    import checkboxEmpDialog from '../../../personnel/group/checkbox-emp-dialog';
    import remoteSearchBatchCodeInput from '../productConfigCotton/components/remote-search-batch-code-input';
    import checkboxProductDialog from '../../order/components/checkbox-product-dialog';
    import { productionPrdMachineView } from '@/api/production/xsOpen';
    import { spinWorkshopProductBatchPage } from '@/api/material/workshopProductBatch';
    import remoteSearchProductInput from './components/remote-search-product-input/index.vue';
    import {
        productionFeedstockTotalCreate,
        productionFeedstockTotalUpdate,
        productionFeedstockTotalGet
    } from '../../../../api/production/feedingMaterialTotal';
    import {
        systemEmpPage,
        workforceManagementScheduleEmpGetByPost
    } from '../../../../api/production/feedMaterial';
    import { workforcemanagementShiftPage } from '../../../../api/schedule/shift';
    import {
        systemDataConfigCreate,
        systemDataConfigPage,
        systemDataConfigUpdate
    } from '../../../../api/basicData/dataConfig';
    export default {
        components: {
            checkboxProductDialog,
            remoteSearchBatchCodeInput,
            remoteSearchProductInput,
            checkboxEmpDialog
        },
        name: '',
        props: {
            // 页面权限的前缀
            permissionPrefix: {
                type: String,
                default: ''
            },
            dialogState: {
                type: Boolean,
                default: false
            },
            dataId: {
                type: [String, Number],
                default: ''
            }
        },
        mixins: [calHeight],
        data() {
            return {
                alterValue: 0,
                alterHHValue: 0,
                visible: false,
                weight: null,
                roleIds: [],
                staffArray: [],
                scheduleShiftList: [],
                createDialogState: false,
                workshopList: [],
                checkboxEmpDialogState: false,
                productionLineList: [],
                showDialog: false,
                showLoading: true,
                saveBtnLoading: false,
                staffList: [],
                validRules: {
                    valMax: [{ required: true, message: '名称必须填写' }]
                },
                ruleForm: {
                    belongDate: '',
                    batchCode: '',
                    batchId: null,
                    billDate: '',
                    code: '',
                    warehouseQty: null,
                    empList: [{ id: null, name: '', feedstockPercentage: null }],
                    datalist: [],
                    productCode: '',
                    productId: null,
                    productName: '',
                    warehouseNumber: '',
                    productionLineCode: '',
                    productionLineId: null,
                    productionLineName: '',
                    shiftId: null,
                    shiftCode: '',
                    shiftName: '',
                    workshopCode: '',
                    workshopId: null,
                    allQty: null,
                    workshopName: ''
                },
                rules: {
                    empList: {},
                    belongDate: [{ required: true, trigger: 'change' }],
                    productionLineId: [{ required: true, trigger: 'change' }],
                    shiftId: [{ required: true, trigger: 'change' }],
                    warehouseNumber: [{ required: true, trigger: 'change' }],
                    datalist: [{ required: true, trigger: 'change' }]
                },
                updatedEmpList: [],
                rawMaterialList: [],
                printedNumbers: [],
                shiftList: [],
                printedHHNumbers: [],
                weightId: null,
                weightCode: null
            };
        },
        methods: {
            onWarehouseChange(e) {
                this.$set(this.ruleForm, 'allQty', this.ruleForm.warehouseQty * e);
                console.log(this.ruleForm.warehouseQty * e);
            },
            onWeight() {
                this.visible = false;
                const params = {
                    auditState: 1,
                    code: 'MCZL',
                    id: null,
                    name: '每仓重量',
                    type: 1,
                    value: this.weight
                };
                if (this.ruleForm.warehouseQty) params.id = this.weightId;
                const api = this.ruleForm.warehouseQty
                    ? systemDataConfigUpdate
                    : systemDataConfigCreate;
                return api(params).then((res) => {
                    this.tableLoading = false;
                    if (res.data.status === 200) {
                        this.getDataConfig();
                        this.$tipsBar(this, 'save');
                    }
                });
            },
            getDataConfig() {
                this.tableLoading = true;
                const params = {
                    pageNo: 1,
                    pageSize: 100,
                    code: 'MCZL'
                };
                return systemDataConfigPage(params).then((res) => {
                    this.tableLoading = false;
                    if (res.data.status === 200) {
                        this.ruleForm.warehouseQty =
                            res.data.res.length > 0
                                ? Number(res.data.res[0].value)
                                : 0;
                        this.weightId =
                            res.data.res.length > 0
                                ? Number(res.data.res[0].id)
                                : 0;
                        this.weightCode =
                            res.data.res.length > 0
                                ? Number(res.data.res[0].value)
                                : 0;
                        this.$set(
                            this.ruleForm,
                            'allQty',
                            this.ruleForm.warehouseQty *
                                this.ruleForm.warehouseNumber
                        );
                    }
                });
            },
            getRawMaterial() {
                this.tableLoading = true;
                return spinWorkshopProductBatchPage(this.searchParams).then(
                    (res) => {
                        this.tableLoading = false;
                        if (res.data.status === 200) {
                            this.rawMaterialList = res.data.res || [];
                        }
                    }
                );
            },
            isEmpDisabled(empId, currentIndex) {
                return this.ruleForm.empList.some((item, index) => {
                    return index !== currentIndex && item.id === empId;
                });
            },
            onAddFeedstock() {
                this.ruleForm.empList.push({
                    id: null,
                    name: '',
                    feedstockPercentage: null
                });
            },
            onDelFeedstock(index) {
                this.ruleForm.empList.splice(index, 1);
            },
            onStaffListChange(index) {
                // 根据选择的id找到对应名字，自动赋值
                const selectedId = this.ruleForm.empList[index].id;
                const staff = this.staffList.find((s) => s.empId === selectedId);
                if (staff) {
                    this.ruleForm.empList[index].name = staff.empName;
                }
            },
            // onStaffListChange(id) {
            //     this.updatedEmpList = [];
            //     e.forEach(id => {
            //         const selectedItem = this.staffList.find(option => option.empId === id);
            //         if (selectedItem) {
            //             // 根据需要构造对象，这里直接包含了id, name, code
            //             this.updatedEmpList.push({
            //                 id: selectedItem.empId,
            //                 name: selectedItem.empName,
            //                 code: selectedItem.empCode
            //             });
            //         }
            //     });
            //     this.ruleForm.empList = this.updatedEmpList;
            // },
            getAssembleList() {
                this.staffList = [];
                const params = {
                    pageNo: 1,
                    pageSize: 100,
                    onJob: true,
                    postId: '96'
                };
                return systemEmpPage(params).then((res) => {
                    if (res.data.status === 200) {
                        res.data.res
                            ? res.data.res.forEach((x) => {
                                x.empId = x.id;
                                x.empName = x.name;
                                delete x.id;
                                delete x.name;
                            })
                            : [];
                        this.staffList = res.data.res;
                    }
                });
            },
            getWorkforceManagementScheduleEmplist(id) {
                const params = {
                    workshopId: this.ruleForm.workshopId,
                    shiftId: id,
                    belongDate: this.ruleForm.belongDate,
                    // postId: '96',
                    postName: '装仓 '
                };
                return workforceManagementScheduleEmpGetByPost(params).then(
                    (res) => {
                        if (res.data.status === 200) {
                            this.staffList = res.data.res || [];
                        }
                    }
                );
            },
            // 获取区域的班次
            getShiftListByWorkshopRequest() {
                this.shiftList = [];
                if (!this.ruleForm.workshopId) return;
                return workforcemanagementShiftPage({
                    workshopId: this.ruleForm.workshopId
                }).then((res) => {
                    if (res.data.status === 200) {
                        this.shiftList = res.data.res || [];
                    }
                });
            },
            onScheduleShiftChange(e) {
                let item = {};
                if (e) {
                    item = this.shiftList.find((x) => x.id === e);
                } else {
                    item = {
                        id: null,
                        shiftId: null,
                        shiftName: null,
                        scheduleId: null
                    };
                }
                this.$set(this.ruleForm, 'shiftId', item.id);
                this.$set(this.ruleForm, 'shiftCode', item.code);
                this.$set(this.ruleForm, 'shiftName', item.name);
                this.ruleForm.datalist = [];
                this.getWorkforceManagementScheduleEmplist(item.id);
            },
            onDateTimeChange(e) {
                this.$set(this.ruleForm, 'shiftId', null);
                this.$set(this.ruleForm, 'shiftName', null);
                this.$set(this.ruleForm, 'shiftId', null);
                this.$set(this.ruleForm, 'billDate', formatDate(e));
                this.scheduleShiftList = [];
                this.getDateScheduleShiftOptionRequest();
            },
            getDateScheduleShiftOptionRequest() {
                if (this.ruleForm.workshopId && this.ruleForm.billDate) {
                    return workforcemanagementScheduleList({
                        belongDate: [
                            this.ruleForm.billDate,
                            this.ruleForm.billDate
                        ],
                        workshopId: this.ruleForm.workshopId
                    }).then((res) => {
                        if (res.data.status === 200) {
                            const resData = res.data.res;
                            if (resData && resData.length) {
                                this.scheduleShiftList =
                                    resData[0].scheduleShiftList;
                            } else {
                            // tipsBar(this, 'custom', 'warning', '当前时间未排班，请排班后再操作！');
                            }
                        }
                    });
                }
            },
            onPrdLineChange(e) {
                const item = this.productionLineList.find((x) => x.id === e);
                this.$set(this.ruleForm, 'productionLineId', item.id);
                this.$set(this.ruleForm, 'productionLineCode', item.code);
                this.$set(this.ruleForm, 'productionLineName', item.name);
                this.$set(this.ruleForm, 'productName', item.productName);
                this.$set(this.ruleForm, 'productId', item.productId);
                this.$set(this.ruleForm, 'productCode', item.productCode);
                this.$set(
                    this.ruleForm,
                    'batchCode',
                    item.batchCode ? item.batchCode : '无'
                );
            },
            autoCalculateFeedstockPercentage() {
                const list = this.ruleForm.empList;

                // 统计已填写和未填写的占比
                const filled = [];
                const unfilledIndexes = [];

                list.forEach((item, index) => {
                    const val = parseFloat(item.feedstockPercentage);
                    if (!isNaN(val)) {
                        filled.push(val);
                    } else {
                        unfilledIndexes.push(index);
                    }
                });
                const totalFilled = filled.reduce((sum, val) => sum + val, 0);
                const remaining = 100 - totalFilled;
                // 情况1：全部未填 -> 平均分
                if (unfilledIndexes.length === list.length) {
                    const avg = (100 / list.length).toFixed(2);
                    list.forEach((item) => {
                        item.feedstockPercentage = avg;
                    });
                } else if (unfilledIndexes.length === 1) {
                    // 情况2：只剩一个未填
                    const index = unfilledIndexes[0];
                    list[index].feedstockPercentage = (
                        remaining > 0 ? remaining : 0
                    ).toFixed(2);
                } else if (unfilledIndexes.length > 1) {
                    // 情况3：多个未填 -> 平均剩余值
                    const avg = (remaining / unfilledIndexes.length).toFixed(2);
                    unfilledIndexes.forEach((index) => {
                        list[index].feedstockPercentage = remaining > 0 ? avg : 0;
                    });
                } else {
                    // 情况4：全部已填写 -> 检查总和是否为100
                    if (totalFilled > 100) {
                        this.$tipsBar(this, 'custom', 'warning', '总占比不能大于100%');
                        return false;
                    } else if (totalFilled < 100) {
                        this.$tipsBar(this, 'custom', 'warning', '总占比不能小于100%');
                        return false;
                    }
                }
                return true;
            },
            getParamData() {
                this.$set(
                    this.ruleForm,
                    'billDate',
                    formatDate(this.ruleForm.belongDate)
                );
                // 如果自动计算占比未通过校验，就终止保存
                const isValid = this.autoCalculateFeedstockPercentage();
                if (!isValid) return;
                const params = JSON.parse(JSON.stringify(this.ruleForm));

                return params;
            },

            createAndUpdateRequest() {
                this.saveBtnLoading = true;
                // 新增
                if (!this.dataId) {
                    this.ruleForm.id = null;
                    productionFeedstockTotalCreate(this.getParamData()).then(
                        (res) => {
                            this.saveBtnLoading = false;
                            if (res.data.status === 200) {
                                this.$tipsBar(this, 'save');
                                this.$emit('on-finish');
                            }
                        }
                    );
                    return;
                }

                // 编辑
                productionFeedstockTotalUpdate(this.getParamData()).then((res) => {
                    this.saveBtnLoading = false;
                    if (res.data.status === 200) {
                        this.$tipsBar(this, 'save');
                        this.$emit('on-finish');
                    }
                });
            },
            onConfirmBtn() {
                this.$refs['ruleForm'].validate((valid) => {
                    if (valid) {
                        this.createAndUpdateRequest();
                    } else {
                        this.$tipsBar(this, 'validator');
                    }
                });
            },
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
                if (!e) {
                    Object.assign(this.$data, this.$options.data());
                    this.$nextTick(() => {
                        this.$refs.ruleForm.resetFields();
                    });
                }
            },
            getDetailRequest() {
                return productionFeedstockTotalGet({ id: this.dataId }).then(
                    (res) => {
                        if (res.data.status === 200) {
                            const resData = res.data.res || {};
                            if (resData.empList) {
                                if (!resData.datalist) {
                                    resData.datalist = [];
                                }
                                resData.empList.forEach((x) => {
                                    resData.datalist.push(x.id);
                                });
                            }
                            this.ruleForm = resData;
                        }
                    }
                );
            },
            getProductionLineListRequest() {
                const params = {
                    workshopId: this.ruleForm.workshopId,
                    processCodes: ['QH']
                };
                return productionPrdMachineView(params).then((res) => {
                    if (res.data.status === 200) {
                        this.productionLineList = res.data.res;
                    }
                });
            },
            async getDependentData() {
                this.showLoading = true;
                this.workshopList =
                    this.$store.state.user.userWorkshop.workshopList;
                this.workshopList =
                    this.$store.state.user.userWorkshop.workshopList.find(
                        (x) => x.code === 'QF'
                    );
                this.$set(this.ruleForm, 'workshopId', this.workshopList.id);
                this.$set(this.ruleForm, 'workshopCode', this.workshopList.code);
                this.$set(this.ruleForm, 'workshopName', this.workshopList.name);
                this.$set(this.ruleForm, 'billDate', formatDate(Date.now()));
                if (!this.ruleForm.belongDate && !this.dataId) {
                    this.$set(this.ruleForm, 'belongDate', formatDate(Date.now()));
                }
                await this.getShiftListByWorkshopRequest();
                await this.getRawMaterial();
                await this.getDataConfig();
                if (this.dataId) await this.getAssembleList();
                await this.getProductionLineListRequest();
                if (this.dataId) await this.getDetailRequest();
                await this.getDateScheduleShiftOptionRequest();
                this.showLoading = false;
            }
        },
        watch: {
            dialogState(newVal) {
                this.showDialog = newVal;
                if (newVal) {
                    this.getDependentData();
                }
            },
            'ruleForm.empList': {
                handler(newVal) {
                    // 清空旧规则
                    this.$set(this.rules, 'empList', {});
                    // 遍历每一项，生成对应的动态规则
                    newVal.forEach((item, index) => {
                        // 设置投料人必填规则
                        this.$set(this.rules.empList, `empList[${index}].id`, [
                            {
                                required: true,
                                message: '请选择投料人',
                                trigger: 'change'
                            }
                        ]);
                    });
                },
                deep: true,
                immediate: true // 保证初始化也会触发
            }
        }
    };
</script>
<style scoped>
.box {
    display: flex;
    align-items: center;
    justify-content: center;
}

.tabLeft {
    width: 100%;
    margin-right: 10px;
}

.tabRight {
    width: 100%;
}
</style>
